package com.xw.unification.utils.http.client;

import com.xw.unification.utils.JacksonUtils;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Optional;

public class HttpRequestBodyBuilder extends HttpRequestBuilder {

    private Object body;

    private Charset charset;

    HttpRequestBodyBuilder(HttpRequestBase request, CloseableHttpClient httpClient) {
        super(request, httpClient);
    }

    public HttpRequestBuilder body(Object body) {
        return body(body, (Charset) null);
    }

    public HttpRequestBuilder body(Object body, String charsetName) {
        Charset charset = Charset.forName(charsetName);
        return body(body, charset);
    }

    public HttpRequestBuilder body(Object body, Charset charset) {
        this.body = body;
        this.charset = Optional.ofNullable(charset).orElse(StandardCharsets.UTF_8);
        return this;
    }

    protected void parseBeforeRequest(HttpRequestBase request) {
        parseBody(request);
    }

    protected void parseBody(HttpRequestBase request) {
        if (body == null || !(request instanceof HttpEntityEnclosingRequestBase)) {
            return;
        }
        HttpEntityEnclosingRequestBase entityRequest = (HttpEntityEnclosingRequestBase) request;
        // do nothing
        String json = JacksonUtils.json(body);
        if (json != null) {
            entityRequest.setEntity(new StringEntity(json, charset));
        }
    }

}

